// 图片压缩函数
// maxSize: 图片的最大尺寸（像素），默认为1200。
// 当图片的宽度或高度超过这个值时，会按比例缩小到这个尺寸
export const compressImage = (file, maxSize = 1200) => {
  try {
    if (file instanceof File) {
      return compressFileImage(file, maxSize)
    } else if (typeof file === 'string' && file.startsWith('data:image')) {
      return compressBase64Image(file, maxSize)
    } else {
      return Promise.reject(new Error('不支持的图片格式'))
    }
  } catch (error) {
    console.error('图片压缩失败:', error)
    return Promise.reject(error)
  }
}

// 压缩文件类型的图片
const compressFileImage = (file, maxSize) => {
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        compressBase64Image(e.target.result, maxSize).then(resolve).catch(reject)
      }
      reader.onerror = () => reject(new Error('文件读取失败'))
    } catch (error) {
      reject(error)
    }
  })
}

// 压缩 Base64 类型的图片
const compressBase64Image = (base64, maxSize) => {
  return new Promise((resolve, reject) => {
    try {
      const img = new Image()
      img.src = base64
      img.onload = () => {
        try {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          
          let width = img.width
          let height = img.height
          
          if (width > height && width > maxSize) {
            height = Math.round((height * maxSize) / width)
            width = maxSize
          } else if (height > maxSize) {
            width = Math.round((width * maxSize) / height)
            height = maxSize
          }
          
          canvas.width = width
          canvas.height = height
          
          ctx.drawImage(img, 0, 0, width, height)
          
          resolve(canvas.toDataURL('image/jpeg', 0.7))
        } catch (error) {
          reject(error)
        }
      }
      img.onerror = () => reject(new Error('图片加载失败'))
    } catch (error) {
      reject(error)
    }
  })
}

// 验证图片文件
export const validateImage = (file, options = {}) => {
  const {
    maxSize = 10, // 默认最大 10MB
    allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  } = options

  // 验证文件类型
  const isValidType = allowedTypes.includes(file.type)
  if (!isValidType) {
    throw new Error('只能上传图片文件')
  }

  // 验证文件大小
  const isValidSize = file.size / 1024 / 1024 < maxSize
  if (!isValidSize) {
    throw new Error(`图片大小不能超过 ${maxSize}MB`)
  }

  return true
}